<?php
namespace app\common\lib\module_config;

use app\common\lib\model_operate\Tools;
use app\common\lib\model_operate\Trace;
use think\Db;

/**
 * 表单控件类
 */
class FormCtrl
{
    private $base; //主表信息

    private $app; //模块应用名

    private $tag; //标签

    protected $config = [
        'title'       => '',
        'field'       => '',
        'option'      => [], //显示项
        'default'     => '', //控件默认值
        'placeholder' => '',
        'is_show'     => '',
    ];

    public function __construct(Trace $trace, $tags)
    {
        $this->tag   = $tags;
        $this->app   = $trace->getApp();
        $this->trace = $trace;
        //设置主表信息
        $this->setBase();
    }

    /**
     * 设置主表信息
     */
    private function setBase()
    {
        //主表名
        $this->base['tableName'] = Tools::tableNameFormat($this->trace->getApp(), 1);
        //获取主表字段
        $this->base['tableInfo']     = DB::getTableInfo($this->base['tableName']);
        $this->base['displayFields'] = [];
    }

    /**
     * 获取主表信息
     */
    public function getBase()
    {
        return $this->base;
    }

    public function setApp($app)
    {
        $this->app = $app;
    }

    public function setTag($tag)
    {
        $this->tag = $tag;
    }

    protected $tg = [
        'text'      => 'setText',
        'select'    => 'setSelect',
        'textarea'  => 'setTextarea',
        'date'      => 'setDate',
        'oneimage'  => 'setOneImage',
        'moreimage' => 'setMoreImage',
        'checkbox'  => 'setCheckbox',
        'radio'     => 'setRadio',
        'open'      => 'setOpen',
        'ueditor'   => 'setUeditor',
        'htmlpage'  => 'setHtmlpage',
    ];

    public function setHtml(&$config)
    {
        $ctrl_type = $config['ctrl_type'];

        $cc = $this->tg[$ctrl_type];

        $result = $this->$cc($config);

        return $result;
    }

    public function setList(array $list)
    {
        $this->list = $list;
    }

    /**
     * 获取模块中html.json文件
     */
    public function getHtmlConfig()
    {

        $module_name = $this->app;

        $res = getModuleConfig($module_name, 'config', 'html.json');

        $res = json_decode($res, true);

        if (!empty($res['html'])) {

            return $res['html'];
        }

        return $res;
    }

    /**
     * 引入页
     */
    public function setHtmlpage(&$config)
    {
        $controller = $config;


        if (empty($config['html'])) {
            return '';
        }

        //获取模块中html配置
        $html_config = $this->getHtmlConfig() ?: [];
        $search      = $config['html'];

        $html_config = array_filter($html_config, function ($t) use ($search) {return $t['name'] == $search;});

        if (empty($html_config)) {
            return '';
        }

        $html_config = array_values($html_config)[0];

        if (empty($html_config[$this->tag]['page'])) {
            return '';
        }

        $page = $html_config[$this->tag]['page'];

        $cto   = explode('@', $page['controller']);
        $class = $cto[0];
        $func  = $cto[1];

        //判断类是否定义
        if (!class_exists($class)) {
            return $class . '类未定义,不能生成html';
        }

        $class = '\\' . $class;

        $cls = new $class();

        //判断类方法是否定义
        if (!method_exists($class, $func)) {
            return $class . '类中' . $func . '方法未定义';
        }

        if ($this->tag != 'add') {
            $list  = $this->list;
            $field = $list[$page['field']];
        } else {
            $field = '';
        }
        
        if ($this->tag == 'search') {
            $html = $cls->$func($config['ctrl_name'], $field);
            return $html;
        }

        $html = $cls->$func($config['field'], $field);

        return $html;
    }

    /**
     * 隐藏框
     */
    public function setHidden(&$config)
    {
        $html = <<<EOF
    <input type="hidden" id="{$config['field']}" name="{$config['field']}" value='{$config['default']}'>
EOF;
        return $html;
    }

    /**
     * 文本
     */
    public function setText(&$config)
    {
        $config = !empty($config) ? $config : $this->config;
        $html   = <<<EOF
<div class="layui-form-item">
    <label class="layui-form-label">{$config['title']}</label>
    <div class="layui-input-block">
        <input type="text" name="{$config['field']}" id="{$config['field']}"  placeholder="{$config['placeholder']}" autocomplete="off" class="layui-input" value='{$config['default']}' >
    </div>
</div>
EOF;
        return $html;
    }

    /**
     * 下拉
     */
    public function setSelect(&$config)
    {
        $config = !empty($config) ? $config : $this->config;

        //设置下拉选项
        $option = '';
        foreach ($config['option'] as $key => $value) {

            $selected = '';
            if ($config['default'] == $key) {
                $selected = 'selected';
            }

            $option .= "<option value='" . $key . "' " . $selected . " >" . $value . "</option>";
        }

        $html = <<<EOF
<div class="layui-form-item">
    <label class="layui-form-label">{$config['title']}</label>
    <div class="layui-input-block">
        <select name="{$config['field']}" id="{$config['field']}" >
            {$option}
        </select>
    </div>
</div>
EOF;
        return $html;
    }

    /**
     * 日期
     */
    public function setDate(&$config)
    {
        $html = <<<EOF
<div class="layui-form-item">
    <label class="layui-form-label">{$config['title']}</label>
    <div class="layui-input-block">
        <input type="text" name="{$config['field']}" id="{$config['field']}" lay-verify="date" placeholder="{$config['placeholder']}" autocomplete="off" class="layui-input" value='{$config['default']}'>
    </div>
</div>
<script>
// window.onload=function(){
    layui.use('laydate', function(){
        var laydate = layui.laydate;laydate.render({elem: "#{$config['field']}" });
    });
// }
</script>
EOF;
        return $html;
    }

    /**
     * 文本域
     */
    public function setTextarea(&$config)
    {
        $html = <<<EOF
<div class="layui-form-item layui-form-text">
    <label class="layui-form-label">{$config['title']}</label>
    <div class="layui-input-block">
        <textarea placeholder="{$config['placeholder']}" id="{$config['field']}"  name="{$config['field']}" class="layui-textarea">{$config['default']}</textarea>
    </div>
</div>
EOF;
        return $html;

    }

    /**
     * 复选框
     */
    public function setCheckbox(&$config)
    {
        $option = '';
        foreach ($config['option'] as $key => $value) {

            $n = array_keys($value)[0];
            $v = array_values($value)[0];

            $checked = '';
            if ($config['default'] == $v) {
                $checked = 'checked';
            }

            $option .= "<input type='checkbox' name='{$n}' value='{$v}' title='{$key}' {$checked}>";
        }

        $html = <<<EOF
<div class="layui-form-item">
    <label class="layui-form-label">{$config['title']}</label>
    <div class="layui-input-block">
        {$option}
    </div>
</div>
EOF;

        return $html;
    }

    /**
     * 单选
     */
    public function setRadio(&$config)
    {

        $option = '';
        foreach ($config['option'] as $key => $value) {

            $n = array_keys($value)[0];
            $v = array_values($value)[0];



            $checked = '';
            if ($config['default'] == $v) {
                $checked = 'checked';
            }

            $option .= '<input type="radio" name='.$n.' value='.$v.' title='.$key.' '.$checked.'>';
        }

        $html = <<<EOF
<div class="layui-form-item">
    <label class="layui-form-label">{$config['title']}</label>
    <div class="layui-input-block">
        {$option}
    </div>
</div>
EOF;
        return $html;
    }

    /**
     * 开关
     */
    public function setOpen(&$config)
    {
        $option = '';

        $checked = '';

        if (!empty($config['option'])) {

            $key = array_keys($config['option']);
            $val = array_values($config['option']);
            $lt  = $val[0] . '|' . $val[1];

            if ($config['default'] == $key['0']) {
                $checked = 'checked';
            }

            $option .= "<input type='hidden' name='{$config['field']}' value='{$key['1']}' >";
            $option .= "<input type='checkbox' name='{$config['field']}' lay-skin='switch' lay-text='{$lt}' value='{$key['0']}' {$checked}>";
        } else {
            if ($config['default'] == 1) {
                $checked = 'checked';
            }

            $option .= "<input type='hidden' name='{$config['field']}' value='2' >";
            $option .= "<input type='checkbox' name='{$config['field']}' lay-skin='switch' lay-text='ON|OFF' value='1' {$checked}>";
        }

        $html = <<<EOF
<div class="layui-form-item">
    <label class="layui-form-label">{$config['title']}</label>
    <div class="layui-input-block">
        {$option}
    </div>
</div>
EOF;
        return $html;
    }

    /**
     * 单图片
     */
    public function setOneImage(&$config)
    {
        $url = cmf_plugin_url('ModuleConfig://admin_index/upload');

        //如果是detail标签 不显示按钮
        $btn = '';
        if ($this->tag != 'detail') {
            $btn = '<button type="button" class="layui-btn" id="' . $config['field'] . '">
                  <i class="layui-icon">&#xe67c;</i>上传图片
                </button>';
        }

        $src = '';
        if (!empty($config['default'])) {

            $is_http = (strpos($config['default'],'http')) === 0 ? true : false;
            if ($is_http) {
                $src = 'src="' . $config['default'] . '"';
            } else {
                $src = 'src="__ROOT__' . $config['default'] . '"';
            }
        }

        $html = <<<EOF

<div class="layui-form-item">
    <label class="layui-form-label">{$config['title']}</label>
    <div class="layui-upload">
        {$btn}
        <input type="hidden" name="{$config['field']}" value="{$config['default']}" id="n-{$config['field']}">
    </div>
    <div class="layui-input-block">
        <div class="layui-upload-list">
            <img {$src} class="layui-upload-img" id="img-{$config['field']}" style="width:92px;height:92px;margin:0 10px 10px 0;">
            <p id="demoText"></p>
            <br>
            <span style="color:red">*图片大小不能超过3M</span>
        </div>
    </div>
</div>


<div style="display:none" class="__is_autoload_js__">
    layui.use('upload', function(){
        var $ = layui.jquery
        ,upload = layui.upload;
        //执行实例
        var uploadInst = upload.render({
            elem: '#{$config['field']}' //绑定元素
            ,url: "{$url}" //上传接口
            ,data:{'app':'{$this->app}','info':'{$config["option"]}'}
            ,method: 'post'
            ,before: function(obj){
                //预读本地文件示例，不支持ie8
                obj.preview(function(index, file, result){
                    $("#img-{$config['field']}").attr('src', result);
                });
            }
            ,done: function(res){
                if ( res.code != 200 ){
                    return layer.msg(res.message,{icon:2,time:1500});
                }
                $("#n-{$config['field']}").val(res.data);
            }
            ,error: function(){
                //请求异常回调
            }
        });
    });
</div>

EOF;
        return $html;

    }

    /**
     * 多图片
     */
    public function setMoreImage(&$config)
    {
        $input = '';
        $image = '';
        if (is_array($config['default']) && !empty($config['default'])) {
            foreach ($config['default'] as $key => $value) {
                $image .= '<div style="display: contents;"><span class="layui-badge" style="position: absolute;">×</span><img src="__ROOT__' . $value . '" class="layui-upload-img" style="width: 92px;height: 92px;margin: 0 10px 10px 0;"><input type="hidden" name="' . $config['field'] . '[]" value="' . $value . '" ></div >';
            }
        }


        //如果是detail标签 不显示按钮
        $btn = '';
        if ($this->tag != 'detail') {
            $btn .= '<div class="layui-upload">
                <button type="button" class="layui-btn" id="btn-' . $config['field'] . '">多图片上传</button>
            </div>';
        }

        // $url  = cmf_plugin_url('ModuleConfig://admin_index/upload') . '?app=' . $this->app;
        $url  = cmf_plugin_url('ModuleConfig://admin_index/upload');
        $root = zy_domain();

        $html = <<<EOF
<div class="layui-form-item">
    <label class="layui-form-label">{$config['title']}</label>
    {$btn}
    <div class="layui-input-block">
        <blockquote class="layui-elem-quote layui-quote-nm" style="margin-top: 10px;">
        预览图：
        <div class="layui-upload-list" id="img-{$config['field']}">{$image}</div>
        </blockquote>
        <br>
        <span style="color:red">*图片大小不能超过3M</span> 
    </div>
    <div id="n-{$config['field']}">
    </div>
</div>
<div style="display:none" class="__is_autoload_js__">
    layui.use('upload', function(){
        var $ = layui.jquery
        ,upload = layui.upload;
        //多图片上传
        upload.render({ 
            elem: '#btn-{$config['field']}'
            ,url: "{$url}" //改成您自己的上传接口
            ,data:{'app':'{$this->app}','info':'{$config["option"]}'}
            ,multiple: true
            ,before: function(obj){
              //预读本地文件示例，不支持ie8
              obj.preview(function(index, file, result){

              });
            },
            done: function(res){
                if (res.code == 200) {
                    let dt = 'src="__ROOT__'+res.data+'"';
                    let field = '{$config["field"]}';
                    let name = 'name="'+field+'[]"';
                    let value = 'value="'+res.data+'"';

                    var html = '<div style="display: contents;"><span class="layui-badge" style="position: absolute;">×</span><img '+dt+' class="layui-upload-img" style="width: 92px;height: 92px;margin: 0 10px 10px 0;"><input type="hidden" '+name+' '+value+' ></div > ';
                    $("#img-"+field).append(html);
                } else {
                    return layer.msg(res.message,{icon:2,time:1500});
                }
            }
        });
        $("#img-{$config['field']}").on('click', '.layui-badge', function () {
            $(this).parent().remove();
        });
    });
</div>
EOF;
// dump($html);exit;
        return $html;
    }


//     /**
//      * 多图片
//      */
//     public function setMoreImage(&$config)
//     {

//         $input = '';
//         $image = '';
//         if (is_array($config['default']) && !empty($config['default'])) {
//             foreach ($config['default'] as $key => $value) {
//                 $input .= '<input type="hidden" name="' . $config['field'] . '[]" value="' . $value . '">';
//                 $image .= '<img src="__ROOT__' . $value . '" alt="" class="layui-upload-img" style="width: 92px;height: 92px;margin: 0 10px 10px 0;">';
//             }
//         }

//         //如果是detail标签 不显示按钮
//         $btn = '';
//         if ($this->tag != 'detail') {
//             $btn .= '<div class="layui-upload">
//                 <button type="button" class="layui-btn" id="btn-' . $config['field'] . '">多图片上传</button>
//             </div>';
//         }

//         $url  = cmf_plugin_url('ModuleConfig://admin_index/upload') . '?app=' . $this->app;
//         $html = <<<EOF
// <div class="layui-form-item">
//     <label class="layui-form-label">{$config['title']}</label>
//     {$btn}
//     <div class="layui-input-block">
//         <blockquote class="layui-elem-quote layui-quote-nm" style="margin-top: 10px;">
//         预览图：
//         <div class="layui-upload-list" id="img-{$config['field']}">{$image}</div>
//         </blockquote>
//     </div>
//     <div id="n-{$config['field']}">
//     {$input}
//     </div>
// </div>
// <div style="display:none" class="__is_autoload_js__">
//     layui.use('upload', function(){
//         var $ = layui.jquery
//         ,upload = layui.upload;
//         //多图片上传
//         upload.render({
//             elem: '#btn-{$config['field']}'
//             ,url: "{$url}" //改成您自己的上传接口
//             ,multiple: true
//             ,before: function(obj){
//               //预读本地文件示例，不支持ie8
//               obj.preview(function(index, file, result){
//                 $('#img-{$config['field']}').append('<img src="'+ result +'" alt="'+ file.name +'" class="layui-upload-img" style="width: 92px;height: 92px;margin: 0 10px 10px 0;">');
//               });
//             }
//             ,done: function(res){
//                 if ( res.code != 200 ){
//                     return layer.msg(res.message,{icon:2,time:1500});
//                 }
//                 $("#n-{$config['field']}").append('<input type="hidden" name="'+{$config['field']}+'[]" value="'+res.data+'" >');
//             }
//         });
//     });
// </div>
// EOF;
//         return $html;
//     }



    public function setUeditor(&$config)
    {

        $html = <<<EOF
<div class="layui-form-item">
    <label class="layui-form-label">{$config['title']}</label>
    <div class="layui-input-block">
        <script type="text/plain" id="{$config['field']}-ueditor" required style="height:500px;" name="{$config['field']}" rows="12">
        {$config['default']}
        </script>
    </div>
</div>
<script type="text/javascript" src="__STATIC__/js/ueditor/ueditor.config.js"></script>
<script type="text/javascript" src="__STATIC__/js/ueditor/ueditor.all.min.js"></script>
<script>
//实例化编辑器
var editor = new UE.ui.Editor();

editor.render("{$config['field']}-ueditor");
</script>
EOF;


        return $html;
    }




}
